package com.foodmarket.service.impl;

import com.foodmarket.mapper.UserMapper;
import com.foodmarket.pojo.Buyers;
import com.foodmarket.pojo.Sellers;
import com.foodmarket.service.UserService;
import com.foodmarket.utils.MD5Util;
import com.foodmarket.utils.ThreadLocalUtil;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper buyerMapper; // 处理买家的Mapper
    @Autowired
    private UserMapper sellerMapper; // 处理卖家的Mapper

    //通过username得到买卖家信息
    @Override
    public Buyers findByBuyerName(String username) {
        Buyers buyer = buyerMapper.findByBuyerName(username);
        return buyer;
    }
    @Override
    public Sellers findBySellerName(String username) {
        Sellers seller = sellerMapper.findBySellerName(username);
        return seller;
    }


    //添加买卖家且对密码进行加密操作
    @Override
    public void registerBuyer(String username, String password,String phone,String email,String name) {
        // 对密码进行加密
        String encryptedPassword = MD5Util.getMD5String(password);
        // 添加买家
        buyerMapper.addBuyer(username, encryptedPassword,phone,email,name);
    }
    @Override
    public void registerSeller(String username, String password,String phone,String email,String name) {
        // 对密码进行加密
        String encryptedPassword = MD5Util.getMD5String(password);
        // 添加卖家
        sellerMapper.addSeller(username, encryptedPassword,phone,email,name);
    }

    //更新买卖家的name以及email信息
    @Override
    public void updateBuyer(Buyers buyers)
    {
        buyerMapper.updateBuyer(buyers);
    }

    @Override
    public void updateSeller(Sellers sellers)
    {
        sellerMapper.updateSeller(sellers);
    }

    //更改买卖家密码
     @Override
        @Transactional
        public void updateBuyerPwd(String newPwd) {
            Map<String,Object> mapBuyer= ThreadLocalUtil.get();
            String username = (String) mapBuyer.get("username");
            buyerMapper.updateBuyerPwd(MD5Util.getMD5String(newPwd),username);

        }
    @Override
        @Transactional
        public void updateSellerPwd(String newPwd) {
        Map<String,Object> mapSeller= ThreadLocalUtil.get();
        String username = (String) mapSeller.get("username");
        buyerMapper.updateSellerPwd(MD5Util.getMD5String(newPwd),username);
    }


}
